var express = require('express');
var router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { Department, Patient } = require('../db/sow');
const { getNextAvailableTime, bookTimeSlot } = require('../scripts/generate-times');

// 获取所有科室列表
router.get('/departments', async (req, res) => {
  try {
    // 执行查询
    const departments = await Department.find()
    
    // 为每个科室添加下一个可用时间
    const departmentsWithNextTime = departments.map(dept => {
      const deptObj = dept.toObject();
      const nextTime = getNextAvailableTime(dept.availableTimes);
      return {
        ...deptObj,
        nextTime: nextTime
      };
    });
    
    res.json({
      success: true,
      data: departmentsWithNextTime
    });
  } catch (error) {
    console.error('获取科室列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取科室列表失败',
      error: error.message
    });
  }
});



// 搜索科室
router.get('/departments/search', async (req, res) => {
  try {
    const { keyword, status = 'active' } = req.query;
    
    if (!keyword) {
      return res.status(400).json({
        success: false,
        message: '请提供搜索关键词'
      });
    }
    
    const query = {
      status,
      $or: [
        { name: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } }
      ]
    };
    
    const departments = await Department.find(query).sort({ sortOrder: 1 });
    
    res.json({
      success: true,
      data: departments
    });
  } catch (error) {
    console.error('搜索科室失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索科室失败',
      error: error.message
    });
  }
});

// 预约时间段
router.post('/departments/:id/book', async (req, res) => {
  try {
    const { date, time, patientId } = req.body;
    
    if (!date || !time || !patientId) {
      return res.status(400).json({
        success: false,
        message: '请提供日期、时间和患者ID'
      });
    }
    
    const department = await Department.findById(req.params.id);
    if (!department) {
      return res.status(404).json({
        success: false,
        message: '科室不存在'
      });
    }
    
    // 尝试预约时间段
    const success = bookTimeSlot(department.availableTimes, date, time, patientId);
    
    if (success) {
      // 保存更新后的数据
      await department.save();
      
      res.json({
        success: true,
        message: '预约成功',
        data: {
          departmentId: department._id,
          date,
          time,
          patientId
        }
      });
    } else {
      res.status(400).json({
        success: false,
        message: '该时间段已被预约或不存在'
      });
    }
  } catch (error) {
    console.error('预约失败:', error);
    res.status(500).json({
      success: false,
      message: '预约失败',
      error: error.message
    });
  }
});

// 获取科室可用时间段
router.get('/departments/:id/times', async (req, res) => {
  try {
    const department = await Department.findById(req.params.id);
    if (!department) {
      return res.status(404).json({
        success: false,
        message: '科室不存在'
      });
    }
    
    res.json({
      success: true,
      data: {
        departmentId: department._id,
        departmentName: department.name,
        availableTimes: department.availableTimes
      }
    });
  } catch (error) {
    console.error('获取可用时间段失败:', error);
    res.status(500).json({
      success: false,
      message: '获取可用时间段失败',
      error: error.message
    });
  }
});

// 配置multer用于文件上传
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = 'uploads/avatars/';
    // 确保目录存在
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'avatar-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 限制文件大小为5MB
  },
  fileFilter: (req, file, cb) => {
    // 只允许图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只允许上传图片文件'), false);
    }
  },
});

// 将图片文件转换为base64（优化版本）
const convertImageToBase64 = (filePath) => {
  try {
    console.log('开始转换图片:', filePath);
    const imageBuffer = fs.readFileSync(filePath);
    console.log('图片文件大小:', imageBuffer.length, 'bytes');
    
    // 检查文件大小，如果太大则压缩
    if (imageBuffer.length > 1024 * 1024) { // 大于1MB
      console.log('图片文件较大，建议压缩');
    }
    
    const base64String = imageBuffer.toString('base64');
    const mimeType = path.extname(filePath).toLowerCase() === '.png' ? 'image/png' : 'image/jpeg';
    const dataUrl = `data:${mimeType};base64,${base64String}`;
    
    console.log('图片转换成功:', {
      mimeType,
      originalSize: imageBuffer.length,
      base64Size: base64String.length,
      dataUrlSize: dataUrl.length,
      preview: dataUrl.substring(0, 50) + '...'
    });
    
    return dataUrl;
  } catch (error) {
    console.error('图片转换失败:', error);
    throw new Error('图片转换失败: ' + error.message);
  }
};

// ==================== 就诊人相关路由 ====================

// 获取所有就诊人列表
router.get('/patients', async (req, res) => {
  try {
    const { userId, status = 'active' } = req.query;
    
    let query = { status };
    
    // 如果提供了用户ID，则只查询该用户的就诊人
    if (userId) {
      query.userId = userId;
    }
    
    const patients = await Patient.find(query)
      .sort({ createdAt: -1 })
      .select('-__v'); // 排除版本字段
    
    res.json({
      success: true,
      data: patients
    });
  } catch (error) {
    console.error('获取就诊人列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取就诊人列表失败',
      error: error.message
    });
  }
});

// 获取单个就诊人详情
router.get('/patients/:id', async (req, res) => {
  try {
    const patient = await Patient.findById(req.params.id).select('-__v');
    
    if (!patient) {
      return res.status(404).json({
        success: false,
        message: '就诊人不存在'
      });
    }
    
    res.json({
      success: true,
      data: patient
    });
  } catch (error) {
    console.error('获取就诊人详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取就诊人详情失败',
      error: error.message
    });
  }
});

// 添加就诊人（支持文件上传）
router.post('/patients', (req, res, next) => {
  upload.single('avatar')(req, res, (err) => {
    if (err) {
      console.error('文件上传错误:', err);
      return res.status(400).json({
        success: false,
        message: '文件上传失败: ' + err.message
      });
    }
    next();
  });
}, async (req, res) => {
  try {
    console.log('收到添加就诊人请求:', req.body); // 调试日志
    console.log('上传的文件:', req.file); // 调试文件信息
    
    const {
      name,
      idCard,
      birthDate,
      gender,
      bloodType,
      maritalStatus,
      specializedTreatment,
      phone,
      emergencyContact,
      emergencyPhone,
      address,
      notes,
      userId
    } = req.body;
    
    // 验证必填字段
    if (!name || !idCard || !birthDate || !gender || !phone) {
      return res.status(400).json({
        success: false,
        message: '请填写所有必填字段：姓名、身份证号、出生日期、性别、手机号'
      });
    }
    
    // 如果没有提供userId，使用默认值或从session中获取
    const finalUserId = userId || '507f1f77bcf86cd799439011'; // 临时默认用户ID
    
    console.log('检查身份证号是否重复...');
    // 检查身份证号是否已存在
    const existingPatient = await Patient.findOne({ idCard });
    if (existingPatient) {
      console.log('身份证号已存在:', existingPatient._id);
      return res.status(400).json({
        success: false,
        message: '该身份证号已存在'
      });
    }
    console.log('身份证号检查通过');
    
    // 处理头像文件
    let avatarData = null;
    if (req.file) {
      try {
        avatarData = convertImageToBase64(req.file.path);
        console.log('头像处理成功，大小:', avatarData.length);
      } catch (error) {
        console.error('头像处理失败:', error);
        return res.status(400).json({
          success: false,
          message: '头像处理失败: ' + error.message
        });
      }
    }
    
    console.log('准备创建就诊人，数据:', {
      name, idCard, birthDate, gender, phone, 
      avatarLength: avatarData ? avatarData.length : 0
    });
    
    console.log('创建Patient实例...');
    // 创建新就诊人
    const newPatient = new Patient({
      name,
      idCard,
      birthDate: new Date(birthDate),
      gender,
      bloodType,
      maritalStatus,
      specializedTreatment,
      phone,
      emergencyContact,
      emergencyPhone,
      address,
      notes,
      avatar: avatarData,
      userId: finalUserId
    });
    console.log('Patient实例创建成功');
    
    console.log('开始保存就诊人到数据库...');
    const savedPatient = await newPatient.save();
    console.log('就诊人保存成功，ID:', savedPatient._id);
    
    res.status(201).json({
      success: true,
      message: '就诊人添加成功',
      data: savedPatient
    });
  } catch (error) {
    console.error('添加就诊人失败:', error);
    console.error('错误详情:', {
      name: error.name,
      message: error.message,
      stack: error.stack
    });
    
    // 处理验证错误
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(err => err.message);
      console.error('验证错误详情:', messages);
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: messages
      });
    }
    
    // 处理重复键错误
    if (error.code === 11000) {
      console.error('重复键错误:', error.keyValue);
      return res.status(400).json({
        success: false,
        message: '身份证号已存在',
        error: error.keyValue
      });
    }
    
    res.status(500).json({
      success: false,
      message: '添加就诊人失败',
      error: error.message
    });
  }
});

// 更新就诊人信息（支持文件上传）
router.put('/patients/:id', upload.single('avatar'), async (req, res) => {
  try {
    console.log('收到更新就诊人请求:', req.body);
    console.log('上传的文件:', req.file);
    
    const {
      name,
      idCard,
      birthDate,
      gender,
      bloodType,
      maritalStatus,
      specializedTreatment,
      phone,
      emergencyContact,
      emergencyPhone,
      address,
      notes,
      status
    } = req.body;
    
    const patient = await Patient.findById(req.params.id);
    if (!patient) {
      return res.status(404).json({
        success: false,
        message: '就诊人不存在'
      });
    }
    
    // 如果更新身份证号，检查是否与其他就诊人冲突
    if (idCard && idCard !== patient.idCard) {
      const existingPatient = await Patient.findOne({ idCard, _id: { $ne: req.params.id } });
      if (existingPatient) {
        return res.status(400).json({
          success: false,
          message: '该身份证号已被其他就诊人使用'
        });
      }
    }
    
    // 处理头像文件
    if (req.file) {
      try {
        const avatarData = convertImageToBase64(req.file.path);
        updateData.avatar = avatarData;
        console.log('头像更新成功，大小:', avatarData.length);
      } catch (error) {
        console.error('头像处理失败:', error);
        return res.status(400).json({
          success: false,
          message: '头像处理失败: ' + error.message
        });
      }
    }
    
    // 更新字段
    const updateData = {};
    if (name) updateData.name = name;
    if (idCard) updateData.idCard = idCard;
    if (birthDate) updateData.birthDate = new Date(birthDate);
    if (gender) updateData.gender = gender;
    if (bloodType !== undefined) updateData.bloodType = bloodType;
    if (maritalStatus !== undefined) updateData.maritalStatus = maritalStatus;
    if (specializedTreatment !== undefined) updateData.specializedTreatment = specializedTreatment;
    if (phone) updateData.phone = phone;
    if (emergencyContact !== undefined) updateData.emergencyContact = emergencyContact;
    if (emergencyPhone !== undefined) updateData.emergencyPhone = emergencyPhone;
    if (address !== undefined) updateData.address = address;
    if (notes !== undefined) updateData.notes = notes;
    if (status) updateData.status = status;
    
    const updatedPatient = await Patient.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true, runValidators: true }
    ).select('-__v');
    
    res.json({
      success: true,
      message: '就诊人信息更新成功',
      data: updatedPatient
    });
  } catch (error) {
    console.error('更新就诊人失败:', error);
    
    if (error.name === 'ValidationError') {
      const messages = Object.values(error.errors).map(err => err.message);
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: messages
      });
    }
    
    res.status(500).json({
      success: false,
      message: '更新就诊人失败',
      error: error.message
    });
  }
});

// 删除就诊人（软删除）
router.delete('/patients/:id', async (req, res) => {
  try {
    const patient = await Patient.findById(req.params.id);
    if (!patient) {
      return res.status(404).json({
        success: false,
        message: '就诊人不存在'
      });
    }
    
    // 软删除：将状态设置为inactive
    patient.status = 'inactive';
    await patient.save();
    
    res.json({
      success: true,
      message: '就诊人删除成功'
    });
  } catch (error) {
    console.error('删除就诊人失败:', error);
    res.status(500).json({
      success: false,
      message: '删除就诊人失败',
      error: error.message
    });
  }
});

// 搜索就诊人
router.get('/patients/search', async (req, res) => {
  try {
    const { keyword, userId, status = 'active' } = req.query;
    
    if (!keyword) {
      return res.status(400).json({
        success: false,
        message: '请提供搜索关键词'
      });
    }
    
    let query = {
      status,
      $or: [
        { name: { $regex: keyword, $options: 'i' } },
        { idCard: { $regex: keyword, $options: 'i' } },
        { phone: { $regex: keyword, $options: 'i' } }
      ]
    };
    
    if (userId) {
      query.userId = userId;
    }
    
    const patients = await Patient.find(query)
      .sort({ createdAt: -1 })
      .select('-__v');
    
    res.json({
      success: true,
      data: patients
    });
  } catch (error) {
    console.error('搜索就诊人失败:', error);
    res.status(500).json({
      success: false,
      message: '搜索就诊人失败',
      error: error.message
    });
  }
});

module.exports = router;
